package sm2

import (
	"crypto/rand"
	"errors"

	"github.com/emmansun/gmsm/sm2"
)

// Sm2Sign 签名数据
// data 待签名数据
// key 私钥
// opts 第一个参数为私钥类型，raw/hex/base64/pem
func Sm2Sign(data, key string, opts ...string) ([]byte, error) {
	// 必须提供私钥类型
	if len(opts) == 0 {
		return nil, errors.New("key type is required")
	}

	keyType := opts[0]
	// 获取私钥
	privateKey, err := ParsePrivateKey(key, KeyType(keyType))
	if err != nil {
		return nil, err
	}

	// uid 获取
	var uid []byte
	if len(opts) > 1 {
		uid = []byte(opts[1])
	}

	// 签名
	signed, err := privateKey.Sign(rand.Reader, []byte(data), sm2.NewSM2SignerOption(true, uid))
	if err != nil {
		return nil, err
	}
	return signed, nil
}

// Sm2VerySign 验证签名是否正确
// data 待签名数据
// sign 签名数据
// pubKey 公钥
// opts 第一个参数为公钥类型,raw/hex/base64/pem
func Sm2VerySign(data, sign string, pubKey string, opts ...string) (bool, error) {
	// 必须提供公钥类型
	if len(opts) == 0 {
		return false, errors.New("key type is required")
	}

	keyType := opts[0]
	// 获取公钥
	publicKey, err := ParsePublicKey(pubKey, KeyType(keyType))
	if err != nil {
		return false, err
	}

	// uid 获取
	var uid []byte
	if len(opts) > 1 {
		uid = []byte(opts[1])
	}

	// 验证签名
	ok := sm2.VerifyASN1WithSM2(publicKey, uid, []byte(data), []byte(sign))
	return ok, nil
}
